/*
 * @Author: 姚杰鸿 adolphus520@163.com
 * @Date: 2025-03-15 01:15:36
 * @LastEditors: 姚杰鸿
 * @LastEditTime: 2025-03-15 22:33:38
 * @Description: file content
 */
import fs from "fs";
import path from "path";
import { Plugin } from "vite";

// 扫描 views 文件夹的函数
function scanViews(dir: string): string[] {
  const files: string[] = [];
  const entries = fs.readdirSync(dir, { withFileTypes: true });
  for (const entry of entries) {
    const fullPath = path.join(dir, entry.name);
    if (entry.isDirectory()) {
      files.push(...scanViews(fullPath));
    } else if (entry.isFile() && /\.(vue|js|ts)$/.test(entry.name)) {
      files.push(fullPath);
    }
  }
  return files;
}

// 定义 Vite 插件
function scanViewsPlugin(): Plugin {
  return {
    name: "scan-views",
    buildStart() {
      const viewsDir = path.resolve(__dirname, "../src/views");
      const viewFiles = scanViews(viewsDir);
      const jsonData = viewFiles.map((file) => {
        const fileName = path.basename(file);
        return {
          value: fileName,
          label: fileName,
        };
      });
      const jsonFilePath = path.resolve(__dirname, "../public/views.json");
      fs.writeFileSync(jsonFilePath, JSON.stringify(jsonData, null, 2));
      console.log("Views JSON file generated:", jsonFilePath);
    },
  };
}

export default scanViewsPlugin;
